#include <stdlib.h>
#include <string.h>
#include "typedef.h"
#include "common.h"
#include "package.h"
#include "taskctrl.h"
#include "env.h"
#include "netctrl.h"
#include "log.h"

void on_handshake(PDATA_PACKAGE package)
{
	PACKAGE data;
	pkg_create_handshakeack_package(&data, g_local_cpus, 1);
	netctrl_send((char*)&data,
			sizeof(PACKAGE)
			);
}

void on_run(PDATA_PACKAGE package)
{
	PRUN_PACKAGE data = (PRUN_PACKAGE)package->command;
	data->id = ntohl ( data->id );

	int length = package->length - sizeof (int) + 1;
	char* task = (char*)malloc( length - sizeof (char));
	for (int i = 0; i < (package->length - sizeof(int)); i++)
	{
		task[i] = package->command[sizeof(int) + i];
	}

	task[length - 1] = '\0';

	if (taskctrl_run(data->id, task) == SUCCESS)
	{
		char message[MAX_PATH] = {0};
		sprintf(message, "RUN --> ID = %d | %s", data->id, task);
		log_alert(LT_NOTICE, message);
	}

	free(task);
}

int on_received(char* buffer, int size)
{
	DATA_PACKAGE package;
	if (pkg_get(&package, buffer, size) != SUCCESS)
	{
		return ERROR;
	}

	switch ( package.type )
	{
	case PT_HANDSHAKE:
		on_handshake(&package);
		break;
	case PT_RUN:
		on_run(&package);
		break;
	default:;
	}

	return SUCCESS;
}

void on_timer()
{
	taskctrl_update();

	int flag = WATCH_FLG_NEW;

	PACKAGE package;
	TASKWATCHINFO taskinfo;
	while(taskctrl_watch(&taskinfo, flag) == WATCH_RET_NOEND)
	{
		if (taskinfo.type == WATCH_TYPE_END)
		{
			pkg_create_finish_package(&package,
					taskinfo.taskId
					);
		}

		netctrl_send((char*)&package,
				sizeof(PACKAGE)
				);

		flag = WATCH_FLG_CONTINUE;
	}
}
